﻿
Imports osi.root.connector
Imports osi.root.formation
Imports osi.root.delegates

Public Class lifetime_binder(Of T As Class)
    Private ReadOnly s As object_unique_pointer_set(Of T) = Nothing

    Public Sub New()
        s = New object_unique_pointer_set(Of T)()
    End Sub

    Public Sub insert(ByVal i As T)
        assert(Not i Is Nothing)
        assert(s.insert(i))
    End Sub

    Public Sub [erase](ByVal i As T)
        assert(Not i Is Nothing)
        assert(s.erase(i))
    End Sub

    Public Function foreach(ByVal d As _do(Of T, Boolean, Boolean)) As Boolean
        If d Is Nothing Then
            Return False
        Else
            Return s.foreach(Function(ByRef x, ByRef y) d(+x, y))
        End If
    End Function

    Public Function foreach(ByVal d As _do(Of T, Boolean)) As Boolean
        If d Is Nothing Then
            Return False
        Else
            Return s.foreach(Function(ByRef x) d(+x))
        End If
    End Function

    Public Function foreach(ByVal d As void(Of T)) As Boolean
        If d Is Nothing Then
            Return False
        Else
            Return s.foreach(Sub(ByRef x) d(+x))
        End If
    End Function

    Public Sub clear()
        s.clear()
    End Sub

    Protected Overrides Sub Finalize()
        GC.KeepAlive(s)
        MyBase.Finalize()
    End Sub
End Class

Public Class lifetime_binder
    Inherits lifetime_binder(Of Object)
End Class

Public Class application_lifetime_binder(Of T As Class)
    Inherits lifetime_binder(Of T)

    Public Shared ReadOnly instance As application_lifetime_binder(Of T) = Nothing

    Shared Sub New()
        instance = New application_lifetime_binder(Of T)()
    End Sub

    Public Sub New()
        AddHandler AppDomain.CurrentDomain().ProcessExit,
                   Sub()
                       clear()
                       waitfor_gc_collect()
                       GC.KeepAlive(Me)
                   End Sub
    End Sub
End Class

Public Class application_lifetime_binder
    Inherits application_lifetime_binder(Of Object)
End Class
